<template>
  <div>
    <input v-model="topic" /> <button @click="sub">sub</button>
    <hr />
    <input v-model="topic2" /> <input v-model="sendMsg" /> <button @click="pub">pub</button>
    <hr />
    <button @click="end">断开mqtt</button>
    <hr />
    <div>接收到的消息：</div>
    <div>{{msg}}</div>
  </div>
</template>

<script>
let mqtt = require('mqtt')
let client = {}
export default {
  name: 'HelloWorld',
  data () {
    return {
      topic: 'test',
      topic2: 'test',
      sendMsg: '我是测试消息',
      msg: ''
    }
  },
  mounted(){
    this.mqttClient('adong')
  },
  methods: {
    sub () {
      this.subscribe(this.topic)
    },
    pub () {
      this.publish(this.topic2, this.sendMsg)
    },
    mqttClient(clientId) {
      client = mqtt('mqtt://127.0.0.1', {
        port: 3003,
        clientId: clientId,
        clean: false
      })
      console.log(client)
      console.log(client.connected)
      client.on('message', (topic, message) => {
        this.msg += "  " + message.toString()
        console.log('message: ', message.toString())
      })
    },
    end() {
      client.end()
    },
    subscribe(topic) {
      client.subscribe(topic, {qos: 1})
      console.log('subscribe:', topic)
    },
    publish(topic, message) {
      client.publish(topic, JSON.stringify(message), {qos: 1})
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
